package logic.dao;

import java.util.LinkedList;
import java.util.List;

import logic.db.DBHelper;

import org.geometerplus.fbreader.book.HighlightingStyle;
import org.geometerplus.zlibrary.core.util.ZLColor;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

/**
 * 高亮的数据访问对象
 * @author zouqp
 * 2014-10-11
 */

public class HighlightingStyleDao
{
	private static HighlightingStyleDao dao;
	private final SQLiteDatabase myDatabase;
	
	private HighlightingStyleDao(Context context) {
		DBHelper dbHelper = DBHelper.getInstance(context);
		myDatabase = dbHelper.getSqliteDatabaseW();
	}
	
	public static HighlightingStyleDao getInstance(Context context) {
		dao = new HighlightingStyleDao(context);
		return dao;
	}
	
	public List<HighlightingStyle> loadStyles() {
		final LinkedList<HighlightingStyle> list = new LinkedList<HighlightingStyle>();
		final String sql = "SELECT style_id,name,bg_color FROM HighlightingStyle";
		final Cursor cursor = myDatabase.rawQuery(sql, null);
		while (cursor.moveToNext())
		{
			list.add(createStyle((int) cursor.getLong(0), cursor.getString(1), (int) cursor.getLong(2)));
		}
		cursor.close();
		return list;
	}
	
	private SQLiteStatement myInsertStyleStatement;
	
	public void saveStyle(HighlightingStyle style) {
		if (myInsertStyleStatement == null)
		{
			myInsertStyleStatement = myDatabase.compileStatement("INSERT OR REPLACE INTO HighlightingStyle (style_id,name,bg_color) VALUES (?,?,?)");
		}
		myInsertStyleStatement.bindLong(1, style.Id);
		final String name = style.getName();
		myInsertStyleStatement.bindString(2, name != null ? name : "");
		final ZLColor bgColor = style.getBackgroundColor();
		myInsertStyleStatement.bindLong(3, bgColor != null ? bgColor.intValue() : -1);
		myInsertStyleStatement.executeInsert();
	}
	
	private HighlightingStyle createStyle(int id, String name, int color) {
		return new HighlightingStyle(id, name, color != -1 ? new ZLColor(color) : null);
	}
	
}
